package com.grapevine.contact.vcard.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.grapevine.contact.data.VCardFile;

import android.os.Environment;

/**
 * Vcard 辅助类
 * 
 * @author zhanwei.zhao
 */
public class VcardUtil
{

	public static final String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath();

	/**
	 * 扫描出SDCARD 上 所有的 vcf 文件
	 * 
	 * @return
	 */
	public static List<VCardFile> scanSdcard() throws IOException
	{
		List<VCardFile> files = new ArrayList<VCardFile>();
		File rootFile = new File(SDCARD_PATH);
		loadVcfFile(files, rootFile);
		return files;
	}

	private static void loadVcfFile(List<VCardFile> list, File file) throws IOException
	{
		if (null == file || !file.exists())
		{
			return;
		}

		if (file.isDirectory())
		{
			File[] files = file.listFiles();

			if (null != files && files.length > 0)
			{
				for (File f : files)
				{
					loadVcfFile(list, f);
				}
			}
		}
		else
		{
			String name = file.getName();
			if (name.toLowerCase().endsWith(".vcf") && file.canRead())
			{
				String canonicalPath = file.getCanonicalPath();
				String fileName = file.getName();
				VCardFile vcardFile = new VCardFile(fileName, canonicalPath, file.lastModified());
				list.add(vcardFile);
				// list.add(file);
			}
		}
	}
}